package cqrtplm.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：lotus
 * @DATE: 2025/7/7 19:03
 */
public class FlowCodeUtil {

    // 有效字母表（排除I/O/Q）
    private static final char[] VALID_LETTERS = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    private static final Map<Character, Integer> LETTER_MAP = new HashMap<>();
    static {
        for (int i = 0; i < VALID_LETTERS.length; i++) {
            LETTER_MAP.put(VALID_LETTERS[i], i);
        }
    }

    /**
     * 生成两位流水码
     * @param index 索引位置 (0-559)
     * @return 两位流水码
     */
    public static String generateSuffix(int index) {
        if (index < 0 || index > 559) {
            throw new IllegalArgumentException("索引必须在0到559之间");
        }

        if (index < 100) {
            return String.format("%02d", index);
        } else if (index < 330) {
            int pos = index - 100;
            char tens = (char) ('0' + pos / 23);
            char unit = VALID_LETTERS[pos % 23];
            return "" + tens + unit;
        } else {
            int pos = index - 330;
            char tens = VALID_LETTERS[pos / 10];
            char unit = (char) ('0' + pos % 10);
            return "" + tens + unit;
        }
    }

    /**
     * 解析两位流水码获取索引位置
     * @param suffix 两位流水码
     * @return 索引位置 (0-559)
     */
    public static int parseSuffix(String suffix) {
        if (suffix == null || suffix.length() != 2) {
            throw new IllegalArgumentException("流水码必须为两位字符");
        }

        char c1 = suffix.charAt(0);
        char c2 = suffix.charAt(1);

        if (Character.isDigit(c1) && Character.isDigit(c2)) {
            return Integer.parseInt(suffix);
        }

        if (Character.isDigit(c1) && LETTER_MAP.containsKey(c2)) {
            int tens = c1 - '0';
            if (tens < 0 || tens > 9) {
                throw new IllegalArgumentException("无效的十位数字: " + c1);
            }
            int unit = LETTER_MAP.get(c2);
            return 100 + (tens * 23) + unit;
        }


        if (LETTER_MAP.containsKey(c1) && Character.isDigit(c2)) {
            int tens = LETTER_MAP.get(c1);
            int unit = c2 - '0';
            if (unit < 0 || unit > 9) {
                throw new IllegalArgumentException("无效的个位数字: " + c2);
            }
            return 330 + (tens * 10) + unit;
        }

        throw new IllegalArgumentException("无效的流水码: " + suffix);
    }
}
